package org.example.designPattern.creation.prototype;

import java.util.ArrayList;
import java.util.List;

/*
*   核心概念：通过拷贝减少频繁创建对象带来的消耗
*   浅拷贝： 对象中的基本类型复制字面量、引用类型复制引用地址
* */
public class ShallowCopy implements Cloneable{
    private String name;
    private List<String> arrayList = new ArrayList<>();


    public ShallowCopy(){
        System.out.println("构造方法执行了！");
        this.name = "qq";
        this.arrayList.add("可怜、无助");
    }

    @Override
    public String toString() {
        return "ShallowCopy{" +
                "name='" + name + '\'' +
                ", arrayList=" + arrayList +
                '}';
    }

    public void setName(String name) {
        this.name = name;
    }



    @Override
    protected ShallowCopy clone() throws CloneNotSupportedException {
        return (ShallowCopy)super.clone();
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        ShallowCopy shallowCopy = new ShallowCopy();
        System.out.println("第一次查看shallowCopy:" + shallowCopy);

        System.out.println("即将开始浅拷贝");
        ShallowCopy clone = shallowCopy.clone();

        System.out.println(clone == shallowCopy);
        clone.setName("胆小、懦弱");
        clone.arrayList.add("胆小、懦弱");
        System.out.println("第二次查看shallowCopy:" + shallowCopy);
    }
}
